package com.example.demo.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.example.demo.dto.DynamicExcelData;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @ClassName: Dyexecle
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/09/08/ 17:17:08
 * @Version 1.0
 */
@Service
public class Dyexecle {
    public static void dynamicExport(HttpServletResponse response,
                                     LinkedHashMap<String, DynamicExcelData> nameMap,
                                     List<Map<String, Object>> list,
                                     String sheetName) throws IOException {
        //首先判断是否有数据，没有就返回
        if(CollUtil.isEmpty(list)){
            return;
        }

        //这里的map使用LinkedHashMap，实现字段的顺序功能
        if(nameMap==null){
            throw new RuntimeException("请填写好映射表数据");
        }

        //先初始化一下传入
        int size = list.size();
        List<List<String>> dataList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            dataList.add(new ArrayList<>());
        }

        //获取表头
        ArrayList<List<String>> head = new ArrayList<>();
        for (Map.Entry<String, DynamicExcelData> titleMap : nameMap.entrySet()) {
            DynamicExcelData data = titleMap.getValue();
            head.add(Collections.singletonList(data.getName()));
        }

        //数据重组
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            List<String> columns = dataList.get(i);
            for (Map.Entry<String, DynamicExcelData> sortNameEntry : nameMap.entrySet()) {
                String key = sortNameEntry.getKey();
                Object value = map.get(key);
                columns.add(value!=null?String.valueOf(value):sortNameEntry.getValue().getDefaultValue());
            }
        }

        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        //使用EasyExcel write进行写出
        EasyExcel.write(response.getOutputStream()).head(head)
                .sheet(sheetName).doWrite(dataList);
    }
}
